package common.webSocket;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class SystemWebSocketHandler implements WebSocketHandler {
    private static Set<WebSocketSession> webSocketSessions = new HashSet<WebSocketSession>();

    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        webSocketSessions.add(webSocketSession);
    }

    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {

    }

    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        webSocketSessions.remove(webSocketSession);
    }

    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        webSocketSessions.remove(webSocketSession);
    }

    public boolean supportsPartialMessages() {
        return false;
    }

    public void sendMessageToUsers(WebSocketMessage message) throws IOException {
        for (WebSocketSession webSocketSession : webSocketSessions) {
            webSocketSession.sendMessage(message);
        }

    }

}